<template>
  <el-dialog
      :title="task?.id ? '编辑检查任务' : '添加检查任务'"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >
      <el-form-item label="检查日期" prop="date">
        <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            :locale="zhCn"
        />
      </el-form-item>
      <el-form-item label="检查类型" prop="checkTypeId">
        <el-select v-model="form.checkTypeId" placeholder="请选择检查类型">
          <el-option
              v-for="type in checkTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="负责医生" prop="doctorId">
        <el-select
            v-model="form.doctorId"
            placeholder="请搜索或选择负责医生"
            filterable
            clearable
            :loading="loadingDoctors"
        >
          <el-option
              v-for="doctor in doctorList"
              :key="doctor.id"
              :label="doctor.doctorName"
              :value="doctor.id"
          />
        </el-select>
      </el-form-item>
      <!-- 编辑模式下显示额外字段 -->
      <template v-if="task?.id">
        <el-form-item label="完成状态" prop="finish">
          <el-switch v-model="form.finish" @change="handleFinishChange"/>
        </el-form-item>
        <el-form-item label="是否异常" prop="hasQuestion">
          <el-switch
              v-model="form.hasQuestion"
              :disabled="!form.finish"
              :active-value="true"
              :inactive-value="false"
          />
        </el-form-item>
        <el-form-item label="检查结果" prop="result">
          <el-input
              v-model="form.result"
              type="textarea"
              :rows="3"
              placeholder="请输入检查结果"
          />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, computed, reactive, watch, nextTick} from 'vue'
import {ElMessage, FormInstance} from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import type {Elder} from '@/types/elder'
import {addCheckTask, updateCheckTask} from '@/api/checkTask'
import {CheckTask} from "@/types/checkTask";
import {CheckType} from "@/types/checkType";
import {Doctor} from "@/types/doctor";
import {getAllDoctors} from "@/api/doctor";

const props = defineProps<{
  modelValue: boolean
  elder: Elder | undefined
  task: CheckTask | undefined
  checkTypes: CheckType[]
  doctorList: Doctor[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const formRef = ref<FormInstance>()
const form = reactive({
  date: '',
  checkTypeId: undefined as number | undefined,
  doctorId: undefined as number | undefined,
  finish: false,
  hasQuestion: false,
  result: '',
  id: undefined as number | undefined
})

const rules = {
  date: [{required: true, message: '请选择检查日期', trigger: 'change'}],
  checkTypeId: [{required: true, message: '请选择检查类型', trigger: 'change'}],
  doctorId: [{required: true, message: '请选择负责医生', trigger: 'change'}]
}

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 添加医生列表相关状态
const loadingDoctors = ref(false)
const doctorList = ref<Doctor[]>([])

// 获取医生列表的方法
const fetchDoctors = async () => {
  if (!props.elder?.communityId) return

  try {
    loadingDoctors.value = true
    //筛选和老人社区id一样的医生
    doctorList.value = props.doctorList.filter(doctor => doctor.communityId === props.elder?.communityId)
  } catch (error) {
    console.error('获取医生列表失败:', error)
    ElMessage.error('获取医生列表失败')
  } finally {
    loadingDoctors.value = false
  }
}

// 监听对话框打开和老人社区ID变化
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    fetchDoctors() // 每次打开对话框时获取最新医生列表
  }
})

// 监听老人社区ID变化
watch(() => props.elder?.communityId, () => {
  if (props.modelValue) { // 只在对话框打开状态下刷新
    fetchDoctors()
  }
})

// 禁用过去的日期
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value || !props.elder) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    const submitData = {
      elderId: props.elder.id,
      childId: props.task?.childId,
      checkTypeId: form.checkTypeId,
      doctorId: form.doctorId,
      date: form.date,
      id: form.id,
      finish: form.id ? form.finish : false,
      hasQuestion: form.id ? form.hasQuestion : false,
      result: form.id ? form.result : ''
    }

    if (form.id) {
      await updateCheckTask(submitData as CheckTask)
      ElMessage.success('更新成功')
    } else {
      await addCheckTask(submitData as CheckTask)
      ElMessage.success('添加成功')
      dialogVisible.value = false
      resetForm() // 提交成功后重置
      emit('success')
    }

    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 完成状态变化时的处理
const handleFinishChange = (isFinished: boolean) => {
  if (!isFinished) {
    // 如果未完成，强制设置为没问题
    form.hasQuestion = false
  }
}
// 修改handleClose方法
const handleClose = () => {
  dialogVisible.value = false
  // 添加重置表单逻辑
  resetForm()
}

// 添加resetForm方法
const resetForm = () => {
  // 使用更彻底的重置方式
  form.date = ''
  form.checkTypeId = undefined
  form.doctorId = undefined
  form.finish = false
  form.hasQuestion = false
  form.result = ''
  form.id = undefined

  // 确保表单验证也重置
  nextTick(() => {
    formRef.value?.resetFields()
  })
}

// 修改watch监听
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    nextTick(() => { // 确保DOM更新完成
      if (props.task) {
        // 编辑模式
        const isFinished = props.task.finish
        const matchedDoctor = props.doctorList.find(d => d.id === props.task?.doctorId)

        Object.assign(form, {
          id: props.task.id,
          date: props.task.date,
          checkTypeId: Number(props.task.checkTypeId),
          doctorId: matchedDoctor ? Number(props.task.doctorId) : undefined,
          finish: isFinished,
          hasQuestion: isFinished ? Boolean(props.task.hasQuestion) : false,
          result: props.task.result || ''
        })
      } else {
        // 添加模式 - 确保完全重置
        resetForm()
      }
    })
  }
}, {immediate: true})
</script>

<style scoped>
/* 禁用状态的样式 */
:deep(.el-switch.is-disabled) {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>